package com.life.muyu.provider;

import com.alibaba.fastjson.JSON;
import com.life.muyu.dto.AccessTokenDTO;
import com.life.muyu.dto.GithubUser;
import okhttp3.*;
import org.springframework.stereotype.Component;
import java.io.IOException;

@Component
public class GithubProvider {
    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        String url = "https://github.com/login/oauth/access_token";

        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String temp = response.body().string();
            return  temp.split("&")[0].split("=")[1];
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public GithubUser getUser(String accessToken){
        String url = "https://api.github.com/user?access_token="+accessToken;
        GithubUser githubUser = null;

        OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                String string = response.body().string();
                githubUser = JSON.parseObject(string, GithubUser.class);
                return githubUser;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
    }
}
